package Secondpagh;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.media.Image;
import android.net.Uri;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.util.Base64InputStream;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.github.mikephil.charting.components.Description;
import com.gyf.immersionbar.ImmersionBar;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONObject;

import java.io.DataInput;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.sql.Array;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.security.auth.callback.Callback;

import SHU.water2.R;
import SHU.water2.Spinnerstyle;
import utils.Auth;
import utils.Base64;

import static SHU.water2.loginin.connection;

public class fix extends AppCompatActivity {
    private int REQUEST_CODE = 1234;
    private String targetUrl = "file:///android_asset/ele.html";

    private ValueCallback<Uri[]> mUploadCallbackAboveL;
    private ValueCallback<Uri> mUploadCallbackBelow;
    private Uri imageUri;
    private String fileName;
    ArrayList<String> imageUrisA;
    ArrayList<String> filenamesA;
    private Spinner spinner1;
    private Spinner spinner2;
    private Spinner spinner3;
    private ArrayAdapter<String> arr_adapter4;
    private ArrayAdapter<String> arr_adapter5;
    private ArrayAdapter<String> arr_adapter6;
    private String[] town;
    private String[] point;
    private String[] site;
    private Handler handler;
    private String sql = "select DISTINCT location_zhen from pump_site";

    private String[] imageUris;
    private String[] filenames;
    private String[] returnKey;
    private String[] getPicGlo;
    private String[] getCheckGlo;
    private String[] getComGlo;
    private String pumpSite;
    private String picDate;

    public WebView webView;
    public WebSettings webSetting;

    @SuppressLint({"SetJavaScriptEnabled", "AddJavascriptInterface", "HandlerLeak"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fix);
        ImmersionBar.with(this).statusBarColor(R.color.color).fitsSystemWindows(true).init();
        handler = new Handler() {
            //接收消息
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                int flag = (int) msg.obj;
                switch (flag) {
                    case 1:
                        spinerset();
                        break;
                    case 2:
                        arr_adapter6 = new Spinnerstyle(fix.this, site);
                        spinner3.setAdapter(arr_adapter6);
                        break;
                    case 3:
                        int key = 0;
                        for (int i = 0; i < getPicGlo.length; i++) {

                            if (getPicGlo[i].equals("1")) {
                                getPicGlo[i] = returnKey[key];
                                key++;
                            }
                        }
                        connect(getCheckGlo, getComGlo, getPicGlo);
                        break;
                }

            }
        };

        imageUrisA = new ArrayList<String>();
        filenamesA = new ArrayList<>();
        initView();
        connect2(sql);

        findViewById(R.id.ret1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }

        });

    }

    //NFC读取
    @Override
    protected void onResume() {
        super.onResume();
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
            readFromTag(getIntent());
        }
    }

    private boolean readFromTag(Intent intent) {
        Parcelable[] rawArray = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
        NdefMessage mNdefMsg = (NdefMessage) rawArray[0];
        NdefRecord mNdefRecord = mNdefMsg.getRecords()[0];
        Log.i("jj", "onRead");
        try {
            if (mNdefRecord != null) {
                String readResult;
                readResult = new String(mNdefRecord.getPayload(), "UTF-8");
                Log.i("jj", readResult);
                return true;
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        ;
        return false;
    }


    //private void connect(String C[], String B[], String P[]) {
    private void connect(String C[], String B[], String P[]) {
        //新建线程连接数据库，防止主界面卡死
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String sql = "INSERT INTO fix_ele VALUES ('" + pumpSite + "',null, ";
                    for (int i = 0; i < C.length; i++) {
                        sql = sql + "'" + C[i] + "', '" + B[i] + "', '" + P[i] + "',";
                    }
                    sql = sql.substring(0, sql.length() - 1) + ")";
                    System.out.println(sql);
                    try {
                        // 创建用来执行sql语句的对象
                        Statement statement = connection.createStatement();
                        statement.executeUpdate(sql);


                    } finally {

                    }
                } catch (SQLException e) {
                    e.printStackTrace();

                }
            }
        }).start();
    }

    private void connect2(String sql) {
        //新建线程连接数据库，防止主界面卡死
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Statement statement = connection.createStatement();
                    if (sql.equals("select DISTINCT location_zhen from pump_site")) {
                        ArrayList<String> L1 = new ArrayList<>();
                        ArrayList<String> L2 = new ArrayList<>();
                        // 创建用来执行sql语句的对象
                        String sql1 = "select DISTINCT location_zhen from pump_site";
                        String sql2 = "select DISTINCT location_point from pump_site";
                        // 执行sql查询语句并获取查询信息
                        ResultSet rSet1 = statement.executeQuery(sql1);
                        statement = connection.createStatement();
                        ResultSet rSet2 = statement.executeQuery(sql2);

                        while (rSet1.next()) {
                            L1.add(rSet1.getString("location_zhen"));
                        }
                        while (rSet2.next()) {
                            L2.add(rSet2.getString("location_point"));
                        }

                        town = new String[L1.size()];
                        point = new String[L2.size()];
                        for (int i = 0; i < L1.size(); i++) {
                            town[i] = (String) L1.get(i);
                        }
                        for (int i = 0; i < L2.size(); i++) {
                            point[i] = (String) L2.get(i);
                        }

                        Message msg = new Message();
                        msg.obj = 1;
                        handler.sendMessage(msg);
                    }

                    if (sql.startsWith("select s", 0)) {
                        ArrayList<String> L1 = new ArrayList<>();
                        // 创建用来执行sql语句的对象
                        String sql1 = sql;
                        // 执行sql查询语句并获取查询信息
                        ResultSet rSet1 = statement.executeQuery(sql1);

                        while (rSet1.next()) {
                            L1.add(rSet1.getString("site_name"));
                        }

                        site = new String[L1.size()];
                        for (int i = 0; i < L1.size(); i++) {
                            site[i] = (String) L1.get(i);
                        }

                        Message msg = new Message();
                        msg.obj = 2;
                        handler.sendMessage(msg);
                    }

                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @SuppressLint("SetJavaScriptEnabled")
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    public void initView() {
        webView = (WebView) findViewById(R.id.fixview);

        webSetting = webView.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setDefaultTextEncodingName("utf-8");
        webSetting.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSetting.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        webSetting.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSetting.setBuiltInZoomControls(true);
        webSetting.setDisplayZoomControls(false);//隐藏缩放控件
        webSetting.setDomStorageEnabled(true);
        webSetting.setAllowUniversalAccessFromFileURLs(true);


        webView.setWebChromeClient(new WebChromeClient() {

            /**
             * (Android 2.2) <= API <= 10(Android 2.3)回调此方法
             */
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                mUploadCallbackBelow = uploadMsg;
                takePhoto();
            }

            /**
             * (Android 3.0) <= API <= 15(Android 4.0.3)回调此方法
             */
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                openFileChooser(uploadMsg);
            }

            /**
             * (Android 4.1.2) <= API <= 20(Android 4.4W.2)回调此方法
             */
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                openFileChooser(uploadMsg);
            }

            /**
             * API >= 21(Android 5.0.1)回调此方法
             */
            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                // (1)该方法回调时说明版本API >= 21，此时将结果赋值给 mUploadCallbackAboveL，使之 != null
                mUploadCallbackAboveL = filePathCallback;
                takePhoto();
                return true;
            }

        });
        webView.addJavascriptInterface(new JsInterface(this), "AndroidWebView");
        webView.loadUrl(targetUrl);//加载要在setting后，否则输入时无法聚焦
    }

    private class JsInterface {
        private Context mContext;

        public JsInterface(Context context) {

            this.mContext = context;
        }

        //在js中调用window.AndroidWebView.showInfoFromJs(name)，便会触发此方法。
        @JavascriptInterface
        public void showInfoFromJs(String getCheck[], String getCom[], String getPic[]) {
            //public void showInfoFromJs(String string, String getCheck[], String getCom[], String getPic[]) {

//            byte[] byteIcon = Base64.decode(string, Base64.DEFAULT);
//            for (int i = 0; i < byteIcon.length; ++i) {
//                if (byteIcon[i] < 0) {
//                    byteIcon[i] += 256;
//                }
//            }
//            //建立一个文件对象
//            File iconFile = new File("userIcon.png");
//            FileOutputStream fos = new FileOutputStream(iconFile);
//            if (!iconFile.exists()) {
//                iconFile.creatNewFile();
//            }
//            //把图片数据写入文件形成图片
//            fos.write(byteIcon);
//            imageUrisA.add(signature);
//            filenamesA.add("signature");

            getPicGlo = getPic;
            getCheckGlo = getCheck;
            getComGlo = getCom;

            imageUris = new String[imageUrisA.size()];
            filenames = new String[filenamesA.size()];
            returnKey = new String[filenamesA.size()];

            for (int i = 0; i < imageUrisA.size(); i++) {
                imageUris[i] = (String) imageUrisA.get(i);
                filenames[i] = (String) filenamesA.get(i);
            }


            UploadManager uploadManager = new UploadManager();
            final boolean[] jug = {true};
            for (int i = 0; i < imageUris.length; i++) {
                int finalI = i;
                uploadManager.put(imageUris[i], filenames[i], Auth.create("YLUAzQSw-RZjvT-IMEs4HwLgc5lcj40sOFcNV4S1", "zqzl80SmehLT5xDB8Bp24gTCGNwohTh-fre9wzlY").uploadToken("fixele"),
                        new UpCompletionHandler() {
                            @Override
                            public void complete(String key, ResponseInfo info, JSONObject res) {
                                // info.error中包含了错误信息，可打印调试
                                // 上传成功后将key值上传到自己的服务器
                                if (info.isOK()) {
                                    String headpicPath = "qsw5fx87y.hd-bkt.clouddn.com/" + key;
                                    System.out.println("complete: " + headpicPath);
                                    returnKey[finalI] = headpicPath;

                                    List<String> returnKeyList = Arrays.asList(returnKey);
                                    if (returnKeyList.contains(null))
                                        Log.i("jj", "上传未完成");
                                    else {
                                        Message msg = new Message();
                                        msg.obj = 3;
                                        handler.sendMessage(msg);
                                    }
                                } else {
                                    jug[0] = false;
                                    Log.i("qiniu", info.error);
                                }
                            }
                        }, null);
            }
            if (jug[0] == true)
                Toast.makeText(mContext, "提交成功", Toast.LENGTH_SHORT).show();
            else
                Toast.makeText(mContext, "提交失败", Toast.LENGTH_SHORT).show();
        }

    }


    /**
     * 调用相机
     */
    private void takePhoto() {
        // 指定拍照存储位置的方式调起相机
        File file = new File(Environment.getExternalStorageDirectory(), "/fixPic/");
        //如果文件夹不存在 就创建文件夹
        if (!file.exists()) {
            file.mkdirs();
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        fileName = df.format(new Date()) + ".jpg";
        File path = new File(Environment.getExternalStorageDirectory() + "/fixPic/" + fileName);
        //imageUri = Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/fixPic/" + fileName));
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(path);
            //file.compress(file.CompressFormat.PNG, 80, fileOutputStream);
            //存储完成后需要清除相关的进程
            fileOutputStream.flush();
            fileOutputStream.close();
            //保存图片后发送广播通知更新数据库
            imageUri = Uri.fromFile(path);
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            intent.setData(imageUri);
            sendBroadcast(intent);
        } catch (FileNotFoundException e) {
            System.out.println("error:" + e.toString());
        } catch (IOException e) {
            System.out.println("error:" + e.toString());
            //LogUtils.i("error:"+e.toString());
        }

        imageUrisA.add(path.getPath());
        filenamesA.add(fileName);

        Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

        Intent Photo = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        Intent chooserIntent = Intent.createChooser(Photo, "选择");

        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});
        startActivityForResult(chooserIntent, REQUEST_CODE);
        //startActivity(captureIntent);
    }

    private String saveBitmap(Bitmap bitmap) {
        //获取需要存储到本地的路径
        File file = new File(Environment.getExternalStorageDirectory(), "/sign/");
        //如果文件夹不存在 就创建文件夹
        if (!file.exists()) {
            file.mkdirs();
        }
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        picDate = df.format(new Date());
        File path = new File(file, "sign" + picDate + ".png");
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(path);
            // compress - 压缩的意思  将bitmap保存到本地文件中
            bitmap.compress(Bitmap.CompressFormat.PNG, 80, fileOutputStream);
            //存储完成后需要清除相关的进程
            fileOutputStream.flush();
            fileOutputStream.close();
            //保存图片后发送广播通知更新数据库
            Uri uri = Uri.fromFile(path);
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            intent.setData(uri);
            sendBroadcast(intent);
        } catch (FileNotFoundException e) {
            System.out.println("error:" + e.toString());
        } catch (IOException e) {
            System.out.println("error:" + e.toString());
            //LogUtils.i("error:"+e.toString());
        }
        System.out.println(path.getPath());
        return path.getPath();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {
            // 经过上边(1)、(2)两个赋值操作，此处即可根据其值是否为空来决定采用哪种处理方法
            if (mUploadCallbackBelow != null) {
                //chooseBelow(resultCode, data);
            } else if (mUploadCallbackAboveL != null) {
                chooseAbove(resultCode, data);
            } else {
                Toast.makeText(this, "发生错误", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * Android API < 21(Android 5.0)版本的回调处理
     *
     * @param resultCode 选取文件或拍照的返回码
     * @param data       选取文件或拍照的返回结果
     */
    private void chooseBelow(int resultCode, Intent data) {
        Log.e("JJ", "返回调用方法--chooseBelow");

        if (RESULT_OK == resultCode) {
            updatePhotos();

            if (data != null) {
                // 这里是针对文件路径处理
                Uri uri = data.getData();
                if (uri != null) {
                    Log.e("JJ", "系统返回URI：" + uri.toString());
                    mUploadCallbackBelow.onReceiveValue(uri);
                } else {
                    mUploadCallbackBelow.onReceiveValue(null);
                }
            } else {
                // 以指定图像存储路径的方式调起相机，成功后返回data为空
                Log.e("JJ", "自定义结果：" + imageUri.toString());
                mUploadCallbackBelow.onReceiveValue(imageUri);
            }
        } else {
            mUploadCallbackBelow.onReceiveValue(null);
        }
//        Message msg = new Message();
//        msg.obj = 3;
//        handler.sendMessage(msg);
        mUploadCallbackBelow = null;
    }

    /**
     * Android API >= 21(Android 5.0) 版本的回调处理
     *
     * @param resultCode 选取文件或拍照的返回码
     * @param data       选取文件或拍照的返回结果
     */
    private void chooseAbove(int resultCode, Intent data) {
        Log.e("JJ", "返回调用方法--chooseAbove");

        if (RESULT_OK == resultCode) {
            updatePhotos();

            if (data != null) {
                // 这里是针对从文件中选图片的处理
                Uri[] results;
                Uri uriData = data.getData();
                if (uriData != null) {
                    results = new Uri[]{uriData};
                    for (Uri uri : results) {
                        Log.e("JJ", "系统返回URI：" + uri.toString());
                    }
                    mUploadCallbackAboveL.onReceiveValue(results);
                } else {
                    mUploadCallbackAboveL.onReceiveValue(null);
                }
            } else {
                Log.e("JJ", "自定义结果：" + imageUri.toString());
                mUploadCallbackAboveL.onReceiveValue(new Uri[]{imageUri});
            }
        } else {
            mUploadCallbackAboveL.onReceiveValue(null);
        }
//        Message msg = new Message();
//        msg.obj = 3;
//        handler.sendMessage(msg);
        mUploadCallbackAboveL = null;
    }

    private void updatePhotos() {
        // 该广播即使多发（即选取照片成功时也发送）也没有关系，只是唤醒系统刷新媒体文件
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        intent.setData(imageUri);
        sendBroadcast(intent);
    }

    public void spinerset() {
        spinner1 = findViewById(R.id.spinner4);
        spinner2 = findViewById(R.id.spinner5);
        spinner3 = findViewById(R.id.spinner6);
        String[] items6 = getResources().getStringArray(R.array.site);


        //适配器3
        arr_adapter4 = new Spinnerstyle(this, town);
        //设置样式
        arr_adapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spinner1.setAdapter(arr_adapter4);
        spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //String spinnerS4 = arr_adapter4.getItem(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        //适配器3
        arr_adapter5 = new Spinnerstyle(this, point);
        //设置样式
        arr_adapter5.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spinner2.setAdapter(arr_adapter5);
        spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String spinnerS5 = arr_adapter5.getItem(position).toString();
                sql = "select site_name from pump_site where location_point =  '" + spinnerS5 + "'";
                connect2(sql);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        //适配器3
        arr_adapter6 = new Spinnerstyle(this, items6);
        //设置样式
        arr_adapter6.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spinner3.setAdapter(arr_adapter6);
        spinner3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //sql = "site_name=" + arr_adapter6.getItem(position).toString();
                pumpSite = arr_adapter6.getItem(position).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }
}
